/*
 * Author: yezi
 * E-mail: okye328@gmail.com
 * Create time: Dec 26, 2012 9:48:04 PM
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

package com.kanbox.linux.operation.http;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kanbox.linux.fs.MountPointManager;

public class RequestFactory {

	private static Logger logger = LoggerFactory
			.getLogger(RequestFactory.class);

	public enum RequestType {
		GET, POST
	}

	public static final String INFO = "https://api.kanbox.com/0/info";
	public static final String LIST = "https://api.kanbox.com/0/list";
	public static final String DOWNLOAD = "https://api.kanbox.com/0/download";
	public static final String UPLOAD = "https://api-upload.kanbox.com/0/upload";
	public static final String DELETE = "https://api.kanbox.com/0/delete";
	public static final String MOVE = "https://api.kanbox.com/0/move";
	public static final String COPY = "https://api.kanbox.com/0/copy";
	public static final String MKDIR = "https://api.kanbox.com/0/create_folder";
	public static final String SHARE = "https://api.kanbox.com/0/share";
	public static final String PENDING_SHARE = "https://api.kanbox.com/0/pendingshares";

	public static HttpUriRequest buildHTTPRequest(String URI,
			String resourcePath, RequestType type, String accessToken,
			BasicNameValuePair... params) {
		HttpUriRequest httpRequest = null;
		if (type == RequestType.GET) {
			httpRequest = buildGet(URI, resourcePath, accessToken, params);
		} else if (type == RequestType.POST) {
			httpRequest = buildPost(URI, accessToken, params);
		}
		return httpRequest;
	}

	private static HttpGet buildGet(String URI, String resourcePath,
			String accessToken, BasicNameValuePair... params) {
		try {
			URIBuilder uriBuilder = null;

			if (resourcePath == null || resourcePath.equals("")) {
				uriBuilder = new URIBuilder(URI);
			} else {
				uriBuilder = new URIBuilder(URI
						+ "/"
						+ URLEncoder.encode(resourcePath, "utf-8").replace("+",
								"%20"));
			}
			for (BasicNameValuePair basicNameValuePair : params) {
				uriBuilder.setParameter(basicNameValuePair.getName(),
						basicNameValuePair.getValue());
			}

			HttpGet httpGet = new HttpGet(uriBuilder.build());
			httpGet.setHeader("Authorization", "Bearer " + accessToken);
			return httpGet;
		} catch (URISyntaxException | UnsupportedEncodingException e) {
			logger.error("URI syntax error", e);
		}
		return null;
	}

	private static HttpPost buildPost(String URI, String accessToken,
			BasicNameValuePair... params) {
		HttpPost httpPost = new HttpPost(URI);
		httpPost.setHeader("Authorization", "Bearer " + accessToken);

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		// formparams.add(new BasicNameValuePair("bearer_token", accessToken));
		for (BasicNameValuePair basicNameValuePair : params) {
			formparams.add(basicNameValuePair);
		}

		UrlEncodedFormEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(formparams, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("Encode not support", e);
		}

		httpPost.setEntity(entity);
		return httpPost;
	}

	/**
	 * 
	 * @param accessToken
	 * @param file
	 * @param params
	 *            only "path" is required
	 * @return
	 */
	public static HttpPost buildUploadFilePost(String accessToken, File file) {
		String path = MountPointManager.localToRemoteDataPath(file
				.getAbsolutePath());
		try {
			path = URLEncoder.encode(path, "utf-8").replace("+", "%20");
		} catch (UnsupportedEncodingException e) {
			logger.error("Unsupported encode.");
		}

		HttpPost httpPost = new HttpPost(UPLOAD + path);
		httpPost.setHeader("Authorization", "Bearer " + accessToken);

		MultipartEntity multipartEntity = new MultipartEntity();
		multipartEntity.addPart("file", new FileBody(file));

		httpPost.setEntity(multipartEntity);

		return httpPost;
	}
}
